package com.example.shoppingcart.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import androidx.annotation.Nullable;

import com.example.shoppingcart.entity.CartInfo;
import com.example.shoppingcart.entity.GoodsInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ShoppingCartDBHelper extends SQLiteOpenHelper {
    private static int DB_VERSION = 1;
    private static String DB_NAME = "shopping.db";
    private static String TABLE_GOODS_INFO = "goods_info";
    private static String TABLE_CART_INFO = "cart_info";
    private static ShoppingCartDBHelper instance = null;

    private SQLiteDatabase reader = null;
    private SQLiteDatabase writer = null;

    private ShoppingCartDBHelper(@Nullable Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    // 单例模式
    public static ShoppingCartDBHelper getInstance(@Nullable Context context) {
        Log.d("zhoutao", "DBHelper.getInstance");
        if (instance == null) {
            instance = new ShoppingCartDBHelper(context);
        }
        return instance;
    }

    // 读-连接
    public SQLiteDatabase openReadLink() {
        Log.d("zhoutao", "openReadLink: ");
        if (reader == null || !reader.isOpen()) {
            reader = instance.getReadableDatabase();
        }
        return reader;
    }

    // 写-连接
    public SQLiteDatabase openWriteLink() {
        Log.d("zhoutao", "openWriteLink: ");
        if (writer == null || !writer.isOpen()) {
            writer = instance.getWritableDatabase();
        }
        return writer;
    }

    // 关闭连接
    public void closeLink() {
        Log.d("zhoutao", "closeLink: ");
        if (reader != null && reader.isOpen()) {
            reader.close();
            reader = null;
        }

        if (writer != null && writer.isOpen()) {
            writer.close();
            writer = null;
        }
    }

    public void insertGoodsInfos(List<GoodsInfo> list) {
        try {
            // 开启事务
            writer.beginTransaction();

            // 遍历插入所有商品信息
            for (GoodsInfo info : list) {
                ContentValues values = new ContentValues();
                values.put("name", info.name);
                values.put("description", info.description);
                values.put("price", info.price);
                values.put("pic_path", info.picPath);
                writer.insert(TABLE_GOODS_INFO, null, values);
                // Log.d("zhoutao", "info: " + info);
            }
            writer.setTransactionSuccessful();
            //  Log.d("zhoutao", "insertGoodsInfos: ");

        } catch (Exception e) {
            Log.d("zhoutao", "insert database fail: ");
        } finally {
            writer.endTransaction();
        }
    }

    public List<GoodsInfo> queryAllGoodsInfo() {
        Log.d("zhoutao", "queryAllGoodsInfo");
        ArrayList<GoodsInfo> list = new ArrayList<>();
        String sql = "SELECT * FROM " + TABLE_GOODS_INFO;
        Cursor cursor = reader.rawQuery(sql, null);

        while (cursor.moveToNext()) {
            int id = cursor.getInt(0);
            String name = cursor.getString(1);
            String desc = cursor.getString(2);
            float price = cursor.getFloat(3);
            String picPath = cursor.getString(4);

            GoodsInfo info = new GoodsInfo();
            info.id = id;
            info.name = name;
            info.description = desc;
            info.price = price;
            info.picPath = picPath;
            list.add(info);
        }
        cursor.close();

        return list;
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        Log.d("zhoutao", "create database");
        // 创建商品信息表
        String goodsInfoTableSQL = "CREATE TABLE IF NOT EXISTS " + TABLE_GOODS_INFO +
                "(" +
                "_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," +
                "name VARCHAR NOT NULL," +
                "description VARCHAR," +
                "price FLOAT," +
                "pic_path VARCHAR" +
                ");";

        sqLiteDatabase.execSQL(goodsInfoTableSQL);

        // 创建购物车信息表
        String cartInfoTableSQL = "CREATE TABLE IF NOT EXISTS " + TABLE_CART_INFO +
                "(" +
                "_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," +
                "goods_id INTEGER NOT NULL," +
                "count INTEGER NOT NULL" +
                ");";

        sqLiteDatabase.execSQL(cartInfoTableSQL);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }

    // 购物车表插入一行
    public void insertCartInfo(int goodsId) {
        CartInfo cartInfo = queryCartInfoByGoodsId(goodsId);
        // Log.d("zhoutao", "insertCartInfo: cartInfo: " + cartInfo);

        ContentValues values = new ContentValues();
        values.put("goods_id", goodsId);

        if (cartInfo == null) {
            // 购物车没有该商品则添加
            values.put("count", 1);
            writer.insert(TABLE_CART_INFO, null, values);
        } else {
            // 购物车有该商品 更新count
            values.put("_id", cartInfo.id);
            values.put("count", ++cartInfo.count);

            writer.update(TABLE_CART_INFO, values, "_id=?", new String[]{String.valueOf(cartInfo.id)});
        }

    }

    private CartInfo queryCartInfoByGoodsId(int goodsId) {
        Cursor cursor = reader.query(
                TABLE_CART_INFO,
                null,
                "goods_id=?",
                new String[]{String.valueOf(goodsId)},
                null,
                null,
                null);

        CartInfo cartInfo = null;

        while (cursor.moveToNext()) {
            cartInfo = new CartInfo();
            cartInfo.id = cursor.getInt(0);
            cartInfo.goodsId = cursor.getInt(1);
            cartInfo.count = cursor.getInt(2);
        }
        cursor.close();

        return cartInfo;
    }

    // 查询购物车中商品总数
    public int countOfCartInfo() {
        int count = 0;

        String sql = "SELECT SUM(count) FROM " + TABLE_CART_INFO;

        Cursor cursor = reader.rawQuery(sql, null);
        if (cursor.moveToNext()) {
            count = cursor.getInt(0);
        }
        cursor.close();

        return count;
    }

    // 查询购物车中所有行
    public List<CartInfo> queryAllGoodsInCart() {
        ArrayList<CartInfo> cartInfoList = new ArrayList<>();

        Cursor cursor = reader.query(TABLE_CART_INFO, null, null, null, null, null, null);
        while (cursor.moveToNext()) {
            CartInfo cartInfo = new CartInfo();
            cartInfo.id = cursor.getInt(0);
            cartInfo.goodsId = cursor.getInt(1);
            cartInfo.count = cursor.getInt(2);

            cartInfoList.add(cartInfo);
        }
        cursor.close();

        return cartInfoList;
    }

    // 根据id查询商品信息
    public GoodsInfo queryGoodsInfoById(int goodsId) {
        GoodsInfo goods = null;

        Cursor cursor = reader.query(TABLE_GOODS_INFO, null, "_id = ?", new String[]{String.valueOf(goodsId)}, null, null, null);

        if (cursor.moveToNext()) {
            goods = new GoodsInfo();
            goods.id = cursor.getInt(0);
            goods.name = cursor.getString(1);
            goods.description = cursor.getString(2);
            goods.price = cursor.getFloat(3);
            goods.picPath = cursor.getString(4);
        }
        cursor.close();

        return goods;
    }

    // 根据商品id删除购物车中的记录
    public void deleteCartInfoByGoodsId(int goodsId) {
        String[] whereArgs = new String[]{String.valueOf(goodsId)};
        writer.delete(TABLE_CART_INFO, "goods_id = ?", whereArgs);
    }

    // 清空购物车表
    public void clearCartInfo() {
        writer.delete(TABLE_CART_INFO, "1=1", null);
    }
}
